import { history, Reducer, Effect } from 'umi';
import { message } from 'antd';
import { startsWith } from 'lodash';
import { fakeAccountLogin } from '@/services/login';
import { TradeResult } from '@/types/global';
import { CurrentUser, StateType, UserLoginRespType } from '@/types/login';
import { deleteCurrentLoginUserId, deleteToken, saveCurrentLoginUserId, saveToken, 
  setAuthority, saveCurrentLoginUser, 
  deleteRoutes,
  deleteButtons} from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const EMPTY: StateType = {
  type: 'account',
  status: 'ok',
  lc: 0,
  currentAuthority: 'admin'
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    ...EMPTY,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response: TradeResult = yield call(fakeAccountLogin, payload);
      console.info(response);
      const { success, result } = response;
      try {
        if (success) {
          const { status, token, userId, type, userName, lc, currentAuthority } = result as UserLoginRespType;
          const loginState: StateType = {
            status,
            type,
            lc,
            currentAuthority
          };
          message.success('🎉 🎉 🎉  登录成功！');
          saveToken(token);
          saveCurrentLoginUserId(userId + "");
          saveCurrentLoginUser(userName);
          yield put({
            type: 'changeLoginStatus',
            payload: loginState
          });
          const userPayload: CurrentUser = {
            userid: userId + ''
          };
          yield put({
            type: 'user/saveCurrentUser',
            payload: userPayload
          });
          // 处理URL
          console.info('currentAuthority', currentAuthority);
          console.info(window.location);
          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          console.info(params);
          let { redirect } = params as { redirect: string };
          if (redirect) {
            // console.info('redirect', redirect);
            // 跳转参数不是http开头，则需要添加
            const { origin } = window.location;
            if (!startsWith(redirect, origin)) {
              redirect = origin + redirect;
            }
            console.info('redirect', redirect);
            const redirectUrlParams = new URL(redirect);
            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substring(urlParams.origin.length);
              if (redirect.match(/^\/.*#/)) {
                redirect = redirect.substring(redirect.indexOf('#') + 1);
              }
              history.replace(redirect);
              return;
            } else {
              window.location.href = '/';
              return;
            }
          }
          // 这里要根据角色做不同的跳转
          // 项目助理跳转至新增需求页面
          // 项目经理跳转至项目怒面板页面
          // 其他人跳转至我的待办页面
          if (currentAuthority.indexOf('assistant') > -1) {
            history.replace('/cq/add');
          } else if (currentAuthority.indexOf('pm') > -1) {
            history.replace('/dashboard/analysis');
          } else {
            history.replace('/workbench/task');
          }
          // window.location.reload();
          return;
        } else {
          const { errorMsg } = response;
          const loginState: StateType = {
            status: 'error',
            type: 'account',
            lc: 0,
            errorMsg
          }
          yield put({
            type: 'changeLoginStatus',
            payload: loginState
          });
        }
      } catch (error) {
        deleteToken();
        deleteCurrentLoginUserId();
        console.error(error);
        message.error('登录失败！');
      }
    },
    logout() {
      const { redirect } = getPageQuery();
      // Note: There may be security issues, please note
      if (window.location.pathname !== '/user/login' && !redirect) {
        deleteToken();
        deleteCurrentLoginUserId();
        deleteRoutes();
        deleteButtons();
        history.replace({
          pathname: '/user/login',
          // search: stringify({
          //   redirect: window.location.href,
          // }),
        });
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        ...payload
      };
    },
  },
};

export default Model;
